package com.gaohe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohe.common.BusinessException;
import com.gaohe.common.Result;
import com.gaohe.mapper.*;
import com.gaohe.pojo.*;
import com.gaohe.pojo.VO.KaiDianVo;
import com.gaohe.service.ShopkeeperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@Slf4j
@Service
public class ShopkeeperServiceImpl extends ServiceImpl<ShopkeeperMapper, Shopkeeper> implements ShopkeeperService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopkeeperMapper shopkeeperMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private StadiumMapper stadiumMapper;
    @Override
    @Transactional
    public Result kaiDian(KaiDianVo kaiDianVo) {
        try {
            //1.user
            User user = kaiDianVo.getUser();
            //主键返回
            userMapper.insert(user);
            //2.shopkeeper
            //userId  username
            Shopkeeper shopkeeper = kaiDianVo.getShopkeeper();
            shopkeeper.setUserId(user.getUserId());
            shopkeeper.setUsername(user.getName());
            shopkeeperMapper.insert(shopkeeper);
            //3.teacher
            Teacher teacher = new Teacher();
            BeanUtils.copyProperties(shopkeeper,teacher);
            teacherMapper.insert(teacher);
            //4.card
            List<CardTemp> CardTemps = kaiDianVo.getCard();
            List<Card> cards = new ArrayList<>();
            for (CardTemp cardTemp : CardTemps) {
                Card card = new Card();
                BeanUtils.copyProperties(cardTemp,card);
                card.setShopkeeperId(shopkeeper.getShopkeeperId());
                cards.add(card);
            }
            cardMapper.insert(cards);
            //5.stadium
//            Stadium stadium = new Stadium();
//            // name sid username addr phone
//            stadium.
            Stadium stadium = kaiDianVo.getStadium();
            stadium.setShopkeeperId(shopkeeper.getShopkeeperId());
            stadium.setUsername(user.getName());
            stadiumMapper.insert(stadium);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("ShopkeeperServiceImpl:kaiDian:出现异常：{}",e.getMessage());
            throw new BusinessException("网络链接不佳，请稍后重试");
        }

    }
}
